package admin.server.controller;

import admin.server.model.param.UmsAdminLoginParam;
import admin.server.model.param.UmsAdminRegisterParam;
import admin.server.model.param.UmsAdminUpdateParam;
import admin.server.service.UmsAdminService;
import admin.server.service.UmsRoleService;
import admin.server.xxljob.SyncEmployeeFromFeiShuJob;
import cn.hutool.core.bean.BeanUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import admin.common.vo.PageVo;
import admin.common.domain.dto.UserDto;
import admin.common.vo.ResponseVO;
import admin.server.dao.UmsEmployeeDao;
import admin.server.model.dto.UmsAdminDetailDto;
import admin.server.model.dto.UmsAdminDto;
import admin.server.model.param.UpdateAdminPasswordParam;
import admin.dao.mapper.UmsEmployeeMapper;
import admin.dao.model.UmsAdmin;
import admin.dao.model.UmsEmployee;
import admin.dao.model.UmsEmployeeExample;
import admin.dao.model.UmsRole;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 后台用户管理
 * Created by zgb on 2018/4/26.
 */
@Slf4j
@Controller
@Tag(name = "后台用户管理")
@RequestMapping("/admin")
public class UmsAdminController {
    @Autowired
    private UmsAdminService adminService;

    @Autowired
    private UmsRoleService roleService;

    @Value("${module.name}")
    private String moduleName;

    @Autowired
    private UmsEmployeeMapper employeeMapper;

    @Autowired
    private UmsEmployeeDao umsEmployeeDao;

    @Autowired
    private SyncEmployeeFromFeiShuJob syncEmployeeFromFeiShuJob;

    @PostConstruct
    public void initResourceRolesMap(){
        umsEmployeeDao.truncate();

    }

    @Operation(summary = "批量获取员工花名册信息:请求头Authorization:Bearer tenantAccessToken，feign已配置RequestInterceptor会把头Authorization传递到RequestTemplate")
    @GetMapping("/employees")
    @ResponseBody
    public ResponseVO<List<UmsEmployee>> employees(@RequestParam(value = "name",required = false) String name) {
        UmsEmployeeExample umsEmployeeExample = new UmsEmployeeExample();
        if(StringUtils.isNotBlank(name)){
            umsEmployeeExample.createCriteria().andNameLike("%".concat(name).concat("%"));
        }
        List<UmsEmployee> umsEmployees = employeeMapper.selectByExample(umsEmployeeExample);
        if(umsEmployees.isEmpty()){
            syncEmployeeFromFeiShuJob.syncEmployeeFromFeiShu();
            umsEmployees = employeeMapper.selectByExample(umsEmployeeExample);
        }

        return ResponseVO.success(umsEmployees);
    }


    @Operation(summary = "用户注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public ResponseVO<UmsAdmin> register(@Validated @RequestBody UmsAdminRegisterParam umsAdminRegisterParam, HttpServletRequest request) throws Exception {
        UmsAdmin umsAdmin = adminService.register(umsAdminRegisterParam,request);
        if (umsAdmin == null) {
            return ResponseVO.failed();
        }
        return ResponseVO.success(umsAdmin);
    }

    @Operation(summary = "登录以后返回token")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseVO login(@Validated @RequestBody UmsAdminLoginParam umsAdminLoginParam) throws Exception {
        return adminService.login(umsAdminLoginParam);
    }

    @Operation(summary = "刷新token")
    @RequestMapping(value = "/refreshToken", method = RequestMethod.GET)
    @ResponseBody
    public ResponseVO refreshToken(String refreshToken) throws Exception {
        return adminService.refreshToken(refreshToken);
    }

    @Operation(summary = "获取当前登录用户信息")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public ResponseVO<UmsAdminDetailDto> getAdminInfo(HttpServletRequest request) throws Exception {
        UmsAdmin umsAdmin = adminService.getCurrentAdmin(request);
        UmsAdminDetailDto umsAdminDetailDto = BeanUtil.toBean(umsAdmin,UmsAdminDetailDto.class);
        umsAdminDetailDto.setMenus(roleService.getMenuList(umsAdmin.getId()));
        umsAdminDetailDto.setRoles(adminService.getRoleList(umsAdmin.getId()));
        return ResponseVO.success(umsAdminDetailDto);
    }

    @Operation(summary = "登出功能")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public ResponseVO logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION) String authHeader) {
        adminService.logout(authHeader);
        return ResponseVO.success(null);
    }

    @Operation(summary = "踢下线")
    @RequestMapping(value = "/kick", method = RequestMethod.POST)
    @ResponseBody
    public ResponseVO kick(@RequestParam String userName) {
        adminService.kick(userName);
        return ResponseVO.success(null);
    }

    @Operation(summary = "根据用户名或姓名分页获取用户列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public ResponseVO<PageVo<UmsAdminDto>> list(@RequestParam(value = "keyword", required = false) String keyword,
                                                  @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                  @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        log.info("moduleName：" + moduleName);
        PageVo<UmsAdminDto> page = adminService.list(keyword, pageSize, pageNum);
        return ResponseVO.success(page);
    }


    @Operation(summary = "获取所有用户")
    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    @ResponseBody
    public ResponseVO<List<UmsAdmin>> listAll() {
        List<UmsAdmin> adminList = adminService.list();
        return ResponseVO.success(adminList);
    }


    @Operation(summary = "获取指定用户信息")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseVO<UmsAdmin> getItem(@PathVariable Long id) {
        UmsAdmin admin = adminService.getItem(id);
        return ResponseVO.success(admin);
    }

    @Operation(summary = "根据ID获取用户详情")
    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseVO<UmsAdminDetailDto> detail(@PathVariable Long id) {
        UmsAdminDetailDto admin = adminService.detail(id);
        return ResponseVO.success(admin);
    }

    @Operation(summary = "修改指定用户信息")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public ResponseVO update(@RequestBody UmsAdminUpdateParam admin) {
        adminService.update(admin);
        return ResponseVO.success();
    }

    @Operation(summary = "修改指定用户密码")
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public ResponseVO updatePassword(@RequestBody UpdateAdminPasswordParam updatePasswordParam) {
        int status = adminService.updatePassword(updatePasswordParam);
        if (status > 0) {
            return ResponseVO.success(status);
        } else if (status == -1) {
            return ResponseVO.failed("提交参数不合法");
        } else if (status == -2) {
            return ResponseVO.failed("找不到该用户");
        } else if (status == -3) {
            return ResponseVO.failed("旧密码错误");
        } else {
            return ResponseVO.failed();
        }
    }

    @Operation(summary = "删除指定用户信息")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public ResponseVO delete(@PathVariable Long id) {
        adminService.delete(id);
        return ResponseVO.success();
    }


    @Operation(summary = "获取指定用户的角色")
    @RequestMapping(value = "/role/{adminId}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseVO<List<UmsRole>> getRoleList(@PathVariable Long adminId) {
        List<UmsRole> roleList = adminService.getRoleList(adminId);
        return ResponseVO.success(roleList);
    }

    @Operation(summary = "根据用户名获取通用用户信息")
    @RequestMapping(value = "/loadByUsername", method = RequestMethod.GET)
    @ResponseBody
    public UserDto loadUserByUsername(@RequestParam String username) {
        UserDto userDTO = adminService.loadUserByUsername(username);
        return userDTO;
    }
}
